package com.summer.user.service.impl;

import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.summer.common.Const;
import com.summer.common.ServerResponse;
import com.summer.common.TokenCache;
import com.summer.user.mapper.UserMapper;
import com.summer.user.pojo.User;
import com.summer.user.pojo.UserLogin;
import com.summer.user.service.IUserService;
import com.summer.util.MD5Util;
import com.summer.util.SendEmailUtil;

/** 
 * @描述：用户 Service 层的实现
 * @作者：yang 
 * @时间：2017年6月22日 下午4:48:47 
 * @版本：1.0
 */
@Service("iUserService")
public class UserServiceImpl implements IUserService {

	@Value("${default.avatar}")
	private String DEFAULT_AVATAR;
	
	@Value("${email.title}")
	private String title;
	
	@Value("${email.content}")
	private String content;
	
	@Value("${prefix}")
	private String prefixUrl;
	
	@Resource
	private UserMapper userMapper;

	@Override
	public ServerResponse<UserLogin> login(String username, String password) {
		int resultCount = userMapper.checkUsername(username);
		if (resultCount == 0) {
			return ServerResponse.createByErrorMessage("用户名不存在！");
		}

		String md5Password = MD5Util.MD5EncodeUtf8(password);
		UserLogin userLogin = userMapper.selectLogin(username, md5Password);
		if (userLogin == null) {
			return ServerResponse.createByErrorMessage("密码错误！");
		}

		return ServerResponse.createBySuccess("登录成功", userLogin);
	}

	@Override
	public ServerResponse<String> register(User user) {
		if(StringUtils.isBlank(user.getUsername())) {
			return ServerResponse.createByErrorMessage("用户名不能为空!");
		}
		if(StringUtils.isBlank(user.getEmail())) {
			return ServerResponse.createByErrorMessage("email不能为空!");
		}
		if(StringUtils.isBlank(user.getPassword())) {
			return ServerResponse.createByErrorMessage("密码不能为空!");
		}
		
		int resultCount = userMapper.checkUsername(user.getUsername());
		if (resultCount > 0) {
			return ServerResponse.createByErrorMessage("用户名已存在！");
		}
		resultCount = userMapper.checkEmail(user.getEmail());
		if (resultCount > 0) {
			return ServerResponse.createByErrorMessage("email已存在！");
		}

		user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
		user.setAvatar(DEFAULT_AVATAR);
		resultCount = userMapper.insertSelective(user);
		if (resultCount == 0) {
			ServerResponse.createByErrorMessage("注册失败！");
		}

		return ServerResponse.createBySuccessMessage("注册成功，请登录！");
	}

	@Override
	public ServerResponse<String> checkValid(String str, String type) {
		if (StringUtils.isNotBlank(type)) {
			int resultCount;
			if (Const.USERNAME.equals(type)) {
				resultCount = userMapper.checkUsername(str);
				if (resultCount > 0) {
					return ServerResponse.createByErrorMessage("用户名已存在！");
				}
			} else if (Const.EMAIL.equals(type)) {
				resultCount = userMapper.checkEmail(str);
				if (resultCount > 0) {
					return ServerResponse.createByErrorMessage("email已存在！");
				}
			} else {
				return ServerResponse.createByErrorMessage("参数错误！");
			}
		} else {
			return ServerResponse.createByErrorMessage("参数错误！");
		}

		return ServerResponse.createBySuccessMessage("校验成功！");
	}

	@Override
	public ServerResponse<String> sendEmailForForget(String email) {
		int resultCount = userMapper.checkEmail(email);
		if (resultCount == 0) {
			return ServerResponse.createByErrorMessage("该邮箱未注册！");
		}

		// token 放入缓存中，备用
		String forgetToken = UUID.randomUUID().toString();
		TokenCache.setKey("token_" + email, forgetToken);
		TokenCache.setKey("email", email);

		// 发送邮件，邮件中内容设置token
		String url = prefixUrl + "/user/forget_reset_pwd/" + TokenCache.getKey("token_" + email);
		return SendEmailUtil.sentMail(email, title, content + url);
	}

	@Override
	public ServerResponse<String> forgetResetPassword(String email, String passwordNew, String forgetToken) {
		if (StringUtils.isBlank(forgetToken)) {
			return ServerResponse.createByErrorMessage("参数错误，token需要传递");
		}
		if (StringUtils.isBlank(passwordNew)) {
			return ServerResponse.createByErrorMessage("密码不能为空！");
		}
		String emailCheck = TokenCache.getKey("email");
		if (!StringUtils.equals(email, emailCheck)) {
			return ServerResponse.createByErrorMessage("email地址被篡改，请重新验证！");
		}
		String token = TokenCache.getKey("token_" + email);
		if (StringUtils.isBlank(token)) {
			return ServerResponse.createByErrorMessage("token无效或者过期！");
		}
		if (StringUtils.equals(token, forgetToken)) {
			String md5Password = MD5Util.MD5EncodeUtf8(passwordNew);
			int resultCount = userMapper.updatePasswordByEmail(email, md5Password);

			if (resultCount > 0) {
				return ServerResponse.createBySuccessMessage("修改密码成功！");
			}
		} else {
			return ServerResponse.createByErrorMessage("token错误，请重新验证！");
		}

		return ServerResponse.createByErrorMessage("修改密码成功失败！");
	}

	@Override
	public ServerResponse<String> resetPassword(String passwordOld, String passwordNew, Integer id) {
		int resultCount = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(passwordOld), id);
		if (resultCount == 0) {
			return ServerResponse.createByErrorMessage("旧密码错误");
		}

		resultCount = userMapper.updatePasswordById(id,MD5Util.MD5EncodeUtf8(passwordNew));
		if (resultCount > 0) {
			return ServerResponse.createBySuccessMessage("密码更新成功！");
		}
		return ServerResponse.createByErrorMessage("密码更新失败！");
	}

	@Override
	public ServerResponse<User> updateInformation(User user) {
		int resultCount = userMapper.checkUsernameByUserId(user.getUsername(), user.getId());
		if(resultCount > 0) {
			return ServerResponse.createByErrorMessage("用户名已被使用，请更换用户名再次尝试更新！");
		}
		resultCount = userMapper.checkEmailByUserId(user.getEmail(), user.getId());
		if(resultCount > 0) {
			return ServerResponse.createByErrorMessage("该邮箱已经被注册，请更换邮箱再次尝试更新！");
		}
		resultCount = userMapper.updateByIdSelective(user);
		if(resultCount > 0) {
			return ServerResponse.createBySuccess("更新个人信息成功！", user);
		}
		return ServerResponse.createByErrorMessage("更新个人信息失败！");
	}

	@Override
	public ServerResponse<User> getInformation(Integer userId) {
		User user = userMapper.selectById(userId);
		if(user == null) {
			return ServerResponse.createByErrorMessage("找不到当前用户！");
		}
		return ServerResponse.createBySuccess(user);
	}

	@Override
	public ServerResponse checkAdminRole(User user) {
		// TODO Auto-generated method stub
		return null;
	}
	
}
